package com.mobimagic.lockscreen.view;

import java.util.Observable;
import java.util.Observer;

import android.content.Context;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;

import com.mobimagic.lockscreen.AppEnv;
import com.mobimagic.lockscreen.view.MobileChargingScrollView.ScrollInfo;
import com.nineoldandroids.view.ViewHelper;

public class FadeView extends View implements Observer{

    private static final boolean DEBUG = AppEnv.bAppdebug;
    private static final String TAG = "FadeView";
    Paint paint;
    LinearGradientDrawable linearGradientDrawable;
    private static final float[] positions = new float[] { 0, 0.6f, 1f };;

    public FadeView(Context context, AttributeSet attrs) {
        super(context, attrs);
        paint = new Paint();
        linearGradientDrawable = new LinearGradientDrawable();
        setBackgroundDrawable(linearGradientDrawable);
    }

    public void onScroll(ScrollInfo scrollInfo) {
        int alpha = 0;
        int range = LayoutData.getInstance().getBottomFadeHeight();
        int deltaY = (int) (scrollInfo.scrollBottomLine - scrollInfo.scrollY);
        if (deltaY > 0) {
            float percent = 1f * deltaY / range;
            alpha = (int) (Math.min(percent, 1) * 255);
            if (DEBUG) {
                Log.d(TAG, "alpha=" + alpha);
            }
        }
        ViewHelper.setAlpha(this, alpha / 255f);
    }

    @Override
    public void update(Observable observable, Object data) {
        if (observable != null && observable instanceof MobileChargeColorHelper && data != null
                && data instanceof ChargeColor) {
            ChargeColor chargeColor = (ChargeColor) data;
            int[] colors = chargeColor.getFadeColor();
            linearGradientDrawable.setColors(colors, positions);
            linearGradientDrawable.invalidateSelf();
        }
    }
}
